package practice3;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Exercise {
    private int count;
    private List<Arithmetic> arithmetics;
    private Random random = new Random();

    public Exercise(int count) {
        this.count = count;
        this.arithmetics = new ArrayList<>(count);
    }

    // 生成加法习题（确保和≤maxNum）
    public void generateAdditions(int maxNum) {
        arithmetics.clear();
        for (int i = 0; i < count; i++) {
            int num1 = random.nextInt(maxNum + 1);
            int num2 = random.nextInt(maxNum - num1 + 1); // 避免和超过maxNum
            arithmetics.add(new Arithmetic(num1, num2, '+'));
        }
    }

    // 生成减法习题（确保差≥0）
    public void generateSubtractions(int maxNum) {
        arithmetics.clear();
        for (int i = 0; i < count; i++) {
            int num1 = random.nextInt(maxNum + 1);
            int num2 = random.nextInt(num1 + 1); // 避免差为负数
            arithmetics.add(new Arithmetic(num1, num2, '-'));
        }
    }

    // 生成混合习题
    public void generateMixed(int maxNum) {
        arithmetics.clear();
        for (int i = 0; i < count; i++) {
            char operator = random.nextBoolean() ? '+' : '-';
            if (operator == '+') {
                int num1 = random.nextInt(maxNum + 1);
                int num2 = random.nextInt(maxNum - num1 + 1);
                arithmetics.add(new Arithmetic(num1, num2, '+'));
            } else {
                int num1 = random.nextInt(maxNum + 1);
                int num2 = random.nextInt(num1 + 1);
                arithmetics.add(new Arithmetic(num1, num2, '-'));
            }
        }
    }

    // 打印习题（每行5道）
    public void print() {
        for (int i = 0; i < arithmetics.size(); i++) {
            System.out.printf("%-15s", arithmetics.get(i).toString());
            if ((i + 1) % 5 == 0) {
                System.out.println();
            }
        }
        System.out.println(); // 换行
    }

    // 获取习题集合（用于测试）
    public List<Arithmetic> getArithmetics() {
        return arithmetics;
    }
}
